Skip to content

PNG: streaming encoder session (IDATs per band, bounded memory) - #17

Merged
sdcb merged 1 commit into
mainfrom
streaming/png-encode
Nov 23, 2026
Merged

sdcb merged 1 commit into
mainfrom
streaming/png-encode

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

What

PngImageEncoder.Create returns a streaming session (StreamingEncoderSession) for a still image:

  • AddFrame: signature, IHDR and every pre-IDAT chunk are written, after all option checks (bad text keyword, TransparentColor on an alpha layout, undefined CompressionLevel throw before any byte reaches the writer).
  • WriteRows: rows are converted to the native layout (BGR→RGB, premultiplied→straight) into a fixed band, filtered with the existing PngWriter.CompressRows, deflated, and emitted as complete IDAT chunks of 64 KiB as soon as each fills.
  • Commit: last IDAT, eXIf / iTXt, IEND.
  • ParallelFragments > 1: each band is one of PngWriter's fragments (ceil(height / fragments) rows), capped at 2 MiB of filtered rows. Bands compress on min(ParallelFragments, ProcessorCount) workers into sync-flushed deflate fragments and are emitted in order. The Adler-32 is combined, as the buffered fragmented path does.
  • Band boundaries depend only on the image size and options, never on how the caller splits WriteRows (tested: one row at a time, random bands, whole, strided).

New file src/Sdcb.SimdCodecs.Png/PngStreamingSession.cs. PngWriter only had three private helpers made internal; its output is unchanged.

Byte-level difference of the default path (please review)

The default options now stream, so default session output changes:

  • The zlib stream is exactly PngWriter's, in the serial path and in the parallel path up to the 2 MiB cap. The filter and deflate calls see the same rows in the same order.
  • Packaging differs. PngWriter writes one IDAT, with its length back-patched. The session writes one IDAT per 64 KiB of zlib stream, which costs 12 bytes per chunk: +0.018% size (1.00018× on every 1920×1080 benchmark case).
  • A file whose zlib stream fits in 64 KiB is byte-identical to PngWriter's. This is why ASessionOfOneFrameIsTheStillPngByteForByte still passes.
  • When the parallel fragments would hold more than 2 MiB of rows (large images), the session cuts the image into more fragments than PngWriter does, so those bytes differ. The size stays within 0.1%, and this is tested.
  • Pixels are identical in every case. Goldens are untouched (none covers session output).

API break: multi-frame sessions need PngWriteOptions.Animation

An APNG's acTL (frame count) must come before the first IDAT, so a session that streams frame 0 cannot later become an animation. I added PngWriteOptions.Animation (bool, default false):

  • Animation = true selects the buffered session: several frames, APNG, same bytes as before.
  • Without it, every PNG session holds one frame (MaxFrames == 1, also with LosslessReduction / Quantize, so the frame limit does not depend on unrelated options).

Break: code from 2.0 that adds several frames to a default-options PNG session now gets InvalidOperationException on the second AddFrame. This needs a line in the release notes. I updated the two in-repo callers (PngApngEncoderTests, AotSmoke/FacadeSmoke). The alternative was to keep the buffered session as the default, which would leave the facade (ImageCodecs.Encode) without streaming. I judged the streaming default the better trade, but this is your call.

Fallbacks (IsStreaming == false, bytes identical to before, tested): LosslessReduction, Quantize, Animation.

Mid-call cancellation: a WriteRows whose token is already cancelled consumes nothing. A token cancelled while the call runs is checked at each band. In that case, or on any other failure part-way through, the session refuses further calls except Dispose. Dispose waits for in-flight workers before it returns pooled memory, and writes nothing more.

Tests (tests/Sdcb.SimdCodecs.Tests/PngStreamingEncodeTests.cs)

  • Every PixelFormat.All entry decodes, through our decoder and through libpng via Magick.NET, to exactly the converted input. Covered at small sizes (default, store, parallel) and at 1031×700 (many IDATs, two parallel bands).
  • EncoderEmitsBeforeCommit, serial and parallel.
  • The same bytes for every WriteRows split. A small file is byte-identical to PngWriter's. A large file carries PngWriter's zlib stream in 64 KiB IDATs. Parallel bands equal the buffered fragments up to the cap.
  • Fallbacks give unchanged bytes, MaxFrames is as described, and bad options are refused before any byte is written.
  • Cancellation; dispose with bands in flight.
  • Memory: an 8192×4096 RGBA frame fed in 64-row bands allocates less than 4 MiB (serial and parallel), using AllocatesLessThan.
  • End to end: a 4000×3000 BGR photo streamed in 37-row bands to a FileStream-backed writer. The test checks the file grows while rows arrive, that no GetSpan asks for more than 1 MiB, and that the file decodes to exact pixels.
  • The test photo is built so Up and Paeth win on many rows. With the original synthetic image, deliberately breaking the row-above carry between bands was not caught; with this one it fails 16 tests.

Runs: full suite 7084 tests, 0 failed. Png classes with REQUIRE_ORACLES=1, DOTNET_EnableAVX2=0 and DOTNET_EnableHWIntrinsic=0: 1689 tests each, 0 failed, 0 skipped. NativeAOT smoke: output identical to JIT. The Wasm smoke was not run; the facade itself is unchanged.

Benchmark (AMD Ryzen 7 5800X, 16 threads, Windows 11, .NET 10.0.15, 1920×1080, synthetic sources)

New contestants streaming / streaming parallel push rows 16 at a time through the session, with their own table in matrix encode. BDN methods were added too. The run was baseline HEAD (main 533b03e) followed by matrix encode --rounds 7; the full report is in benchmarks/Sdcb.SimdCodecs.Png.Benchmarks/results/streaming-encode-2026-11-23-amd-ryzen-7-5800x.md.

  • Existing paths: current ÷ baseline geometric mean is 1.005× over 48 cases. PngWriter code is unchanged; individual cases scatter 0.85–1.20× because other agents' builds were running on the machine.
  • Streaming ÷ buffered (one thread): geometric mean 0.94×. Store is about 0.75×, since no whole-file MemoryStream and ToArray copy is needed. Size is 1.00018×.
  • Streaming parallel ÷ buffered parallel: geometric mean 0.88×, same size ratio.
  • I used the in-process matrix A/B against the freshly built baseline, because this benchmark has no ab command. A BDN run is not included.

For the coordinator / facade

No facade or Abstractions change is needed. The facade's ImageCodecs.CreateEncoder(ImageFormat.Png, …) and Encode stream automatically. A facade caller who wants an APNG passes new PngWriteOptions { Animation = true }.

🤖 Generated with Claude Code

PngImageEncoder.Create now returns a StreamingEncoderSession for a still
image: signature, IHDR and the pre-IDAT chunks at AddFrame, each band of
rows filtered and deflated as it arrives and emitted as complete 64 KiB
IDAT chunks, the trailing chunks and IEND at Commit. Memory is a band of
rows. With ParallelFragments the bands are PngWriter's fragments (capped
at 2 MiB of rows) compressed on min(ParallelFragments, ProcessorCount)
workers and emitted in order.

The zlib stream equals PngWriter's (serial, and parallel up to the cap);
only the IDAT packaging differs, +12 bytes per 64 KiB (+0.018%). A file
whose zlib stream fits 64 KiB is byte-identical. Band boundaries depend
only on the image size and options, never on WriteRows chunking.

LosslessReduction, Quantize and the new PngWriteOptions.Animation keep
the buffered session (IsStreaming false, bytes unchanged). API break: a
session of several frames (APNG) now needs Animation = true; without it
a PNG session holds one frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sdcb
sdcb merged commit bc2372c into main Nov 23, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant